package com.hzdp.netty.showcase.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.marshalling.MarshallingEncoder;

import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import com.hzdp.netty.showcase.protocal.NettyMessage;

public class NettyMessageEncoder extends MessageToMessageEncoder<NettyMessage> {

	private MarshallingEncoder marshallingEncoder;

	public NettyMessageEncoder() {
		marshallingEncoder = new MarshallingEncoder(MarshallingCodecFactory.getMarshallerProvider());
	}

	@Override
	protected void encode(ChannelHandlerContext ctx, NettyMessage msg, List<Object> out) throws Exception {
		ByteBuf sendBuffer = Unpooled.buffer();
		sendBuffer.writeInt(msg.getHeader().getCrcCode());
		sendBuffer.writeInt(msg.getHeader().getLength());
		sendBuffer.writeLong(msg.getHeader().getSessionId());
		sendBuffer.writeByte(msg.getHeader().getType());
		sendBuffer.writeByte(msg.getHeader().getPriority());
		sendBuffer.writeInt(msg.getHeader().getAttachment().size());

		String key = null;
		byte[] keyArray = null;
		Object value = null;

		Set<Entry<String, Object>> entrySet = msg.getHeader().getAttachment().entrySet();
		for (Entry<String, Object> entry : entrySet) {
			key = entry.getKey();
			keyArray = key.getBytes("UTF-8");
			sendBuffer.writeInt(keyArray.length);
			sendBuffer.writeBytes(keyArray);

			value = entry.getValue();
//			marshallingEncoder.e
		}
	}

}
